<?php
  //test query http://localhost/gpstracker/savePoint.php?lat=4807.038+N&lng=01131.000+E&altitude=99&name=NameTest&comment=Comment Test&time=123519&track=0&userLogin=SergioEstevao&userTid=1235656;
  
  include_once('session.php');  
  include_once('db.php');
  
  if ( !IsSessionValid()){
		echo "-1";		
		exit;
	}
    
  if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
  {
    // Read the input from stdin     
    //print_r("[".file_get_contents("php://input")."]");
    $id = $_POST['id'];    
  }
  else
  {
    $id = $_GET['id'];    
  }  
  $target_path = "uploads/";

	$fileName = $_FILES['file']['name'];
	$tmpName  = $_FILES['file']['tmp_name'];
	$fileSize = $_FILES['file']['size'];
	$fileType = $_FILES['file']['type'];

	$fp      = fopen($tmpName, 'r');
	$content = fread($fp, filesize($tmpName));

	$target_path = $target_path . basename( fileName); 
/*
	if(move_uploaded_file(tmpName, $target_path)) {
    echo "The file ". basename( $fileName). 
    " has been uploaded";
	} else{
    echo "There was an error uploading the file, please try again!";
	}
*/       
  $conn = &ADONewConnection($dbType);
  $conn->PConnect($dbServer, $dbUser, $dbPassword, $dbName);
  //$conn->debug = true;
  
  // [TODO:]check if this point where image is being save is owned by this user
    
  $query = "insert into image ( filename, data, id_point, size, type) values (".$conn->qstr($fileName).", null, $id, $fileSize, ".$conn->qstr($fileType).")";
  // execute query      
  if ( $conn->Execute($query) ) {
    $imageId = $conn->Insert_ID();
		$conn->UpdateBlob('image','data',$content,'id_image = '.$imageId);
		echo $imageId;	
	}  else {
		echo "-1";	
	}  
?>
